//
//  ItemNode.cpp
//  ItemViewTest
//
//  Created by bean on 13/5/7.
//  Copyright 2013年 __MyCompanyName__. All rights reserved.
//
#include "CCScrollView.h"
#include "ItemNode.h"

using namespace cocos2d;
using namespace extension;


static const CCSize FRAME_SIZE = CCSize(350, 200);
static const float GAP = 8;
static const CCPoint START_POINT = CCPoint(GAP, GAP);
static const int MAX_COUNT = 50;
ItemNode::ItemNode(void)
{
    
}
ItemNode::~ItemNode(void)
{
    
}
bool ItemNode::init(void)
{
    
    return true;
}
void ItemNode::setScrollSize(cocos2d::CCSize size)
{
    m_frameSize = size;
    CCScrollView* scrollView = CCScrollView::create(m_frameSize);
    scrollView->setBounceable(false);
    CCSprite* itemFrame = CCSprite::create("skill_bg.png");
    m_itemSize = itemFrame->getTextureRect().size;
    
    int rowCount = (m_frameSize.width - START_POINT.x) / (m_itemSize.width + GAP);
    int colCount = MAX_COUNT / rowCount;
    if (MAX_COUNT % rowCount != 0) colCount += 1;
    CCSize contentSize = CCSize(m_frameSize.width, START_POINT.y + (GAP+ m_itemSize.height) * colCount);
    
    m_spiteArray = CCArray::create();
    m_spiteArray->retain();
    for (int r = 0; r < rowCount; r++)
    {
        for (int c = 0; c < colCount; c++)
        {
            CCSprite* itemFrame = CCSprite::create("skill_bg.png");
            scrollView->addChild(itemFrame);
            itemFrame->setPosition(ccp(START_POINT.x + (GAP + m_itemSize.width) * r,
                                       START_POINT.y + (GAP+ m_itemSize.height) * (colCount - c - 1)));
            m_spiteArray->addObject(itemFrame);
        }
    }
    scrollView->setContentSize(contentSize);
    scrollView->setContentOffset(ccp(0, - contentSize.height + m_frameSize.height));
    this->addChild(scrollView);
}

void ItemNode::setDelegate(ItemNodeDelegate *delegate)
{
    m_delegate = delegate;
}

CCSprite* ItemNode::touchStartWithPoint(CCPoint p)
{
    for (int i = 0; i < m_spiteArray->count(); i++) {
        CCSprite* sprite = dynamic_cast<CCSprite*>(m_spiteArray->objectAtIndex(i));
        if (fabsf(p.x - sprite->getPositionX()) < m_itemSize.width &&
            fabsf(p.y - sprite->getPositionY()) < m_itemSize.height) {
            sprite->setScale(1.3);
            return sprite;
        }
    }
    return NULL;
}
void ItemNode::touchEndWithPoint(cocos2d::CCPoint p, cocos2d::CCSprite *s)
{
    
}
void ItemNode::setItems(cocos2d::CCArray* array)
{
//    CCArray *array = ;
//    for (int i = 0; i < m_spiteArray->count(); i++) {
//        CCSprite* sprite = dynamic_cast<CCSprite*>(m_spiteArray->objectAtIndex(i));
//        
//    }
}